<!-- 目录-->
<template>
  <div class="directory-box">
    <div class="flex-center-wrap list-choose">
      <div
        class="flex-center-wrap flex1"
        v-if="!isPackCourse && !isScCourse && !query.isStudy"
      >
        <el-select
          class="list-select"
          :disabled="isPackCourse"
          v-model="playOptions.year"
          placeholder="请选择"
          :popper-append-to-body="false"
          @change="switchCourse(1)"
        >
          <el-option
            v-for="(value, key) in isPackCourse
              ? coursePackInfo
              : courseInfo.yearTeacherMap"
            :key="key"
            :label="key"
            :value="key"
          ></el-option>
        </el-select>
      </div>
      <div class="flex-center-wrap flex1 rel">
        <el-select
          class="list-select"
          v-model="playOptions.teacher_id"
          placeholder="请选择"
          :popper-append-to-body="false"
          @change="switchCourse"
          :disabled="query.isStudy"
        >
          <el-option
            v-for="item in teacherList"
            :key="item.teacher_id"
            :label="item.teacher_name"
            :value="item.teacher_id"
          ></el-option>
        </el-select>
        <!-- 私教学习中心切换大纲老师入口 -->
        <div
          class="private-change-entry flex-center-wrap"
          v-if="query.outline_id"
          @click="openChooseTeacher"
        >
          <div>切换</div>
          <i class="iconfont icon-qiehuanjihua"></i>
        </div>
      </div>
    </div>
    <div class="play-list">
      <template v-if="!isShowListPlaceholder">
        <div v-for="(item, index) in playList" :key="Math.random(0, 1) + index">
          <div
            class="dir-name-wrapper flex-center-wrap"
            v-if="item.dir_name"
            @click.prevent="toggleDir(item)"
          >
            <div class="flex-center-wrap">
              <div
                class="flex-center dir-icon-box"
                :class="{ 'dir-icon-rotate': item.isExpand }"
              >
                <i class="iconfont icon-youjiantou dir-icon"></i>
              </div>
              <div
                :width="troggleWidth"
                :style="{
                  'max-width': troggleWidth
                    ? (+item.is_placeholder > 0
                        ? troggleWidth - 80
                        : troggleWidth) + 'px'
                    : +item.is_placeholder > 0
                    ? '190px'
                    : '268px'
                }"
                class="dir-name text-ess-1"
              >
                {{ item.dir_name }}
              </div>
            </div>
            <div
              v-if="+item.is_placeholder > 0"
              :class="[
                'ml6',
                'section-update-label',
                +item.is_placeholder === 1
                  ? 'section-update-label-1'
                  : 'section-update-label-2'
              ]"
            >
              {{ +item.is_placeholder === 1 ? '待更新' : '更新中' }}
            </div>
            <!-- <div class="dir-r flex1"></div> -->
          </div>
          <play-section v-else :section="item" />
          <play-item
            v-if="item.children && item.children.length && item.isExpand"
            :children="item.children"
            :maxWidth="troggleWidth"
          ></play-item>
        </div>
      </template>
      <div v-else class="mk-placeholder-box flex-center-wrap flex-column-wrap">
        <img
          class="mk-placeholder-img"
          src="//image.zlketang.com/public/news/images/new_official/play/mk-placeholder-img.png"
          alt=""
        />
        <span>很抱歉，课程暂未更新</span>
      </div>
    </div>
    <!-- 私教班切换老师弹框 -->
    <change-teacher ref="changeTeacher"></change-teacher>
  </div>
</template>
<script>
import playSection from '@/components/play/playSection.vue'
import playItem from '@/components/play/playItem.vue'
import changeTeacher from '@/pages/study_center/private_study_center/components/changeTeacher.vue'
export default {
  name: 'playList',
  components: {
    'play-item': playItem,
    'play-section': playSection,
    'change-teacher': changeTeacher //私教班切换老师
  },
  data() {
    return {
      // 播放目录对象
      playOptions: {},
      // 播放列表
      playList: [],
      // 是否展示
      teacherList: [],
      // 是否显示目录缺省状态
      isShowListPlaceholder: false,
      firstSection: {},
      troggleWidth: ''
    }
  },
  computed: {
    // 当前课程目录信息
    courseMkInfo() {
      return this.$store.state.play.courseMkInfo || {}
    },
    // 权限集
    coursePackInfo() {
      return this.$store.state.play.coursePackInfo
    },
    // 权限
    courseInfo() {
      return this.$store.state.play.courseInfo || {}
    },
    selectInfo() {
      return this.$store.state.play.selectInfo || {}
    },
    isPackCourse() {
      return this.$store.state.play.isPackCourse
    },
    // 当前正在播放的课节信息
    playingSection() {
      return this.$store.state.play.playingSection || {}
    },
    isScCourse() {
      return this.$store.state.play.isScCourse
    },
    isLogin() {
      return this.$store.state.user.isLogin
    },
    // 获取链接参数
    query() {
      return this.getQuery(location.search)
    }
  },
  methods: {
    //打开私教学习中心切换老师弹框
    openChooseTeacher() {
      this.$refs.changeTeacher.openTeacherChoose()
    },
    // 初始化显示目录内容
    async init() {
      let { teacher_id, year, course_id } = this.courseMkInfo
      this.playOptions = { teacher_id, year }
      await this.getCourseProgress(course_id)
      this.dealPlayOptions()
      this.getTeachers()
      this.$bus.$on('openDir1', val => {
        this.playList.forEach(item => {
          if (+item.dir_id === +val.dir.dir_id) {
            item.isExpand = true
          }
        })
      })
    },
    // 获取当前课程进度
    async getCourseProgress(course_id) {
      // 获取看课进度
      await this.$store.dispatch('play/getVideoProgress', {
        course_id
      })
    },
    // 判断是否有课节
    hasSection(options) {
      return options.some(item => {
        if (item.children && item.children.length) {
          return this.hasSection(item.children)
        } else {
          return item.video_detail || item.live_detail
        }
      })
    },
    // 处理播放的目录
    async dealPlayOptions() {
      let { options = [], course_id } = this.courseMkInfo
      this.isShowListPlaceholder = false
      if (!options || !options.length || !this.hasSection(options)) {
        //没有课节的情况
        this.isShowListPlaceholder = true
      }
      if (!options || !options.length) {
        this.$store.commit('play/setVideoImgType', 2)
        this.$message({
          type: 'warning',
          message: '课程暂未更新，老师正在快马加鞭更新中~'
        })
        return
      }
      // 获取上一次观看的课节id
      let last_vid = this.$store.state.play.courseLastVid
      let obj = {}
      if (last_vid) {
        this.getCourseSectionId(last_vid, options, obj)
      }
      let course_section_id = obj.course_section_id
      //如果是私教学习中心跳转过来的则定位到链接中的课节并且只展示链接中的课节
      let { course_section_id: link_course_section_id, isStudy } = this.query
      if (isStudy) {
        course_section_id = link_course_section_id
      }
      //如果本地缓存中存在课节id，则定位到对应课节并且清除缓存
      if (storage.get('localtion_section_id')) {
        course_section_id = storage.get('localtion_section_id')
        storage.remove('localtion_section_id')
      }
      // 获取课节对应的视频信息
      this.firstSection = {}
      this.$store.commit('play/setVideoImgType', 0)
      this.playList = JSON.parse(
        JSON.stringify(this.setMkList(options, course_section_id))
      )
      if (isStudy) {
        this.playList = [this.firstSection]
      }
      let { teacher_id, year } = this.playOptions
      if (!course_section_id) {
        // 获取第一个课节id
        if (!Object.keys(this.firstSection).length) {
          this.$store.dispatch('play/setSelectInfo', {
            ...this.selectInfo,
            teacher_id,
            year,
            course_id,
            course_section_id: '',
            course_section_name: ''
          })
          this.$store.commit('play/setVideoImgType', 2)
          return this.$message({
            type: 'warning',
            message: '课程暂未更新，老师正在快马加鞭更新中~'
          })
        }
        if (this.firstSection.live_id) {
          //直播课
          let { live_id, item_name } = this.firstSection
          this.$store.commit('play/setVideoImgType', 1)
          this.$store.dispatch('play/setSelectInfo', {
            ...this.selectInfo,
            teacher_id,
            year,
            course_section_id: live_id,
            course_id,
            course_section_name: item_name
          })
          this.setMkZk(this.playList)
          return
        }
        if (
          this.firstSection.video_detail &&
          this.firstSection.video_detail.is_lock &&
          +this.courseInfo.is_purchased === 0
        ) {
          if (!this.isLogin) {
            this.showLoginDialog()
          } else {
            this.$confirm('抱歉，您暂未开通课程权限。', '提示', {
              confirmButtonText: '去开通',
              cancelButtonText: '取消',
              type: 'warning',
              center: true,
              customClass: 'custom-confirm-box'
            })
              .then(res => {
                let product_id = ''
                if (this.isPackCourse) {
                  product_id = this.coursePackInfo.product_id
                } else {
                  product_id = this.courseInfo.product_id
                }
                if (!product_id) {
                  return this.$message({
                    type: 'warning',
                    message: '该课程暂未绑定商品，请联系客服！'
                  })
                }
                this.goTo('/course_detail.html', {
                  query: { product_id },
                  target: '_blank'
                })
              })
              .catch(err => {})
          }
          return
        }
        course_section_id = this.firstSection.item_id
      }
      // 判断播放的视频is_lock是否为 1；
      if (
        this.judgeLock(course_section_id, this.playList) &&
        +this.courseInfo.is_purchased === 0
      ) {
        if (!this.isLogin) {
          this.showLoginDialog()
        } else {
          this.$confirm('抱歉，您暂未开通课程权限。', '提示', {
            confirmButtonText: '去开通',
            cancelButtonText: '取消',
            type: 'warning',
            center: true,
            customClass: 'custom-confirm-box'
          })
            .then(res => {
              let product_id = ''
              if (this.isPackCourse) {
                product_id = this.coursePackInfo.product_id
              } else {
                product_id = this.courseInfo.product_id
              }
              if (!product_id) {
                return this.$message({
                  type: 'warning',
                  message: '该课程暂未绑定商品，请联系客服！'
                })
              }
              this.goTo('/course_detail.html', { query: { product_id } })
            })
            .catch(err => {})
        }
        return
      }

      this.$store.dispatch('play/setSelectInfo', {
        ...this.selectInfo,
        teacher_id,
        year,
        course_section_id,
        course_id,
        course_section_name: this.firstSection.item_name
      })
      this.$store.dispatch('play/setCurVideoProgress', { video_id: last_vid })
      await this.$store.dispatch('play/getPlayingSection', {
        course_section_id,
        course_id
      })
      this.setMkZk(this.playList)
    },
    // 处理课程目录
    setMkList(options, course_section_id) {
      // 递归设置初始展开状态
      options.forEach(item => {
        if (!item.children) {
          // 总时长转换成时分秒
          if (item.duration) {
            item.durationTime = this.timestampToHour(item.duration * 1000, 2)
          }
          if (!Object.keys(this.firstSection).length && !item.is_placeholder) {
            // 没有记录时直接取第一个课节
            if (!course_section_id) {
              this.firstSection = item
              return
            }
            if (item.item_id === course_section_id) {
              //找第一个课节
              this.firstSection = item
            }
          }
          return
        }
        item.isExpand = false
        item.children = this.setMkList(item.children, course_section_id)
      })
      return options
    },
    // 获取视频id对应的课节id
    getCourseSectionId(video_id, options, obj) {
      return options.some(item => {
        if (+item.option_type === 1) {
          //目录
          return this.getCourseSectionId(video_id, item.children, obj)
        } else {
          if (+item.video_id === +video_id) {
            obj.course_section_id = item.item_id
            return true
          }
        }
      })
    },
    // 设置目录展开
    setMkZk(options) {
      return options.some(item => {
        if (!item.children) {
          return (
            (item.video_detail &&
              this.selectInfo.course_section_id ===
                item.video_detail.course_section_id) ||
            (item.live_detail &&
              this.selectInfo.course_section_id === item.live_detail.live_id)
          )
        } else {
          let isExpand = this.setMkZk(item.children)
          item.isExpand = isExpand
          return isExpand
        }
      })
    },
    // 判断课节的is_lock状态
    judgeLock(course_section_id, playList) {
      return playList.some(item => {
        if (!item.children) {
          if (
            item.video_detail &&
            course_section_id === item.video_detail.course_section_id
          ) {
            return item.video_detail.is_lock
          } else if (
            item.live_detail &&
            course_section_id === item.live_detail.course_section_id
          ) {
            return item.live_detail.is_lock
          }
        } else {
          return this.judgeLock(course_section_id, item.children)
        }
      })
    },
    // 切换课程目录
    switchCourse(type) {
      if (type === 1) {
        //切换年份，如果选中的年份有当前选中的老师，则直接查询，否则 选择当前年份的第一个老师查询
        let isHasTeacherF = this.courseInfo.yearTeacherMap[
          this.playOptions.year
        ].some(item => item.teacher_id === this.playOptions.teacher_id)
        if (!isHasTeacherF) {
          //当前选中的老师在当前选中的年份中不存在，则默认选中当前年份中第一个老师
          this.playOptions.teacher_id = this.courseInfo.yearTeacherMap[
            this.playOptions.year
          ][0].teacher_id
        }
      }
      let params = {
        course_id: this.courseMkInfo.course_id,
        teacher_id: this.playOptions.teacher_id,
        year: this.playOptions.year
      }
      this.$store.dispatch('play/getCourseMkInfo', params)
    },
    // 控制展开关闭文件夹
    toggleDir(item) {
      item.isExpand = !item.isExpand
      this.$forceUpdate()
    },
    // 获取老师数据
    getTeachers() {
      let { course_id } = this.courseMkInfo
      if (this.isPackCourse) {
        let { allTeachers, chapters } = this.coursePackInfo[
          this.playOptions.year
        ]
        let teachers = []
        let courseObj = {}
        chapters.some(
          chater =>
            chater.courses &&
            chater.courses.some(course => {
              if (course.course_id === course_id) {
                courseObj = course
                teachers =
                  (Array.isArray(course.teachers) && course.teachers) || []
                return true
              }
            })
        )
        // 强制转为字符串
        teachers = teachers.map(tid => tid + '')
        // teacherList：当前老师列表
        let teacherList = Object.values(allTeachers).filter(item =>
          teachers.includes(item.teacher_id)
        )
        let bindTeacherIndexArr = courseObj.bind_teachers_index
        // 强制转为字符串
        bindTeacherIndexArr =
          (Array.isArray(bindTeacherIndexArr) &&
            bindTeacherIndexArr.map(bindIndexId => bindIndexId + '')) ||
          []
        if (bindTeacherIndexArr.length) {
          // teacherOrdersArr：老师排序数组
          let teacherOrdersArr = []
          // [1] 先按bind_teachers_index进行排序（bind_teachers_index中的id需要包含在teachers里面）
          bindTeacherIndexArr.forEach(tItem => {
            // 校验tItem合法性，必须为数字字符串
            if (/^\d+$/.test(tItem) && teachers.includes(tItem)) {
              teacherOrdersArr.push(tItem)
            }
          })
          // [2] 在将teachers中不包含在bindTeacherIndexArr中的元素加入
          teachers.forEach(tId => {
            // 校验tId合法性，必须为数字字符串
            if (/^\d+$/.test(tId) && !teacherOrdersArr.includes(tId)) {
              teacherOrdersArr.push(tId)
            }
          })
          // sortedTeacherList：排序后的数组
          let sortedTeacherList = []
          teacherOrdersArr.forEach(element => {
            let currentTeacher = teacherList.find(
              c_item => +c_item.teacher_id === +element
            )
            currentTeacher && sortedTeacherList.push(currentTeacher)
          })
          this.teacherList = sortedTeacherList
        } else {
          this.teacherList = teacherList
        }
      } else {
        this.teacherList = this.courseInfo.yearTeacherMap[this.playOptions.year]
      }
    }
  },
  watch: {
    courseMkInfo: {
      handler(val) {
        // 重新渲染目录
        this.init()
      },
      deep: true
    }
  },
  mounted() {
    this.storage.init()
    this.init()
  }
}
</script>
<style scoped>
.directory-box {
  width: 100%;
  height: calc(100% - 94px);
  overflow-x: hidden;
  overflow-y: auto;
  background: #212121;
}
.list-choose {
  background: #1a1a1a;
  border-radius: 4px;
  margin: 0 20px;
}
.directory-box
  /deep/
  .list-choose
  .el-select
  .el-input.is-focus
  .el-input__inner {
  border: none;
}
.directory-box /deep/ .list-choose .el-input__inner {
  background-color: transparent;
  border: none;
  height: 54px;
  color: #8c8c8c;
}
.directory-box /deep/ .el-select-dropdown {
  background: #393939;
  border: none;
}
.directory-box /deep/ .el-select-dropdown__item.selected {
  color: #2f71de;
}
.directory-box /deep/ .el-popper[x-placement^='bottom'] .popper__arrow {
  border-bottom-color: #393939;
}
.directory-box /deep/ .el-popper[x-placement^='bottom'] .popper__arrow::after {
  border-bottom-color: #393939;
}
.directory-box /deep/ .el-select-dropdown__item {
  color: #fff;
}
.directory-box /deep/ .el-select-dropdown__item.hover,
.el-select-dropdown__item:hover {
  background: #4d4d4d;
}
.directory-box /deep/ .el-select .el-input .el-select__caret {
  color: #8c8c8c !important;
}
.directory-box /deep/ .list-select .is-disabled .el-input__suffix {
  display: none;
}
.directory-box /deep/ .el-select .el-input.is-disabled .el-input__inner {
  cursor: unset;
}
/* .list-select {
    width: 135px;
  } */
.play-list {
  position: relative;
  margin-top: 10px;
  height: calc(100% - 74px);
  overflow-y: auto;
  overflow-x: hidden;
}
.dir-name-wrapper {
  padding: 10px 20px;
  cursor: pointer;
}
.dir-name {
  /* width: 240px; */
  font-size: 16px;
  color: #e6e6e6;
  overflow: hidden;
  word-break: break-all;
  /* text-overflow: ellipsis;
  white-space: nowrap;
  word-break: break-all; */
}
.dir-icon-box {
  transition: all 0.1s ease;
  margin-right: 6px;
  width: 16px;
  height: 16px;
}
.dir-icon {
  font-size: 14px;
  color: #e6e6e6;
}
.dir-icon-rotate {
  transform: rotate(90deg);
}
.mk-placeholder-img {
  margin-bottom: 10px;
  width: 122px;
  height: auto;
}
.mk-placeholder-box {
  margin-top: 100px;
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: 400;
  color: #8c8c8c;
  line-height: 20px;
}
.directory-box /deep/ .el-select {
  width: 100% !important;
}
.directory-box /deep/ ::-webkit-scrollbar-thumb {
  background-color: #737373;
}
.directory-box /deep/ ::-webkit-scrollbar-track {
  background-color: #1a1a1a;
}
.section-update-label {
  width: 48px;
  height: 19px;
  line-height: 19px;
  font-size: 12px;
  font-weight: 400;
  text-align: center;
  border-radius: 11px;
}
.section-update-label-1 {
  color: #b3b3b3;
  border: 1px solid #333333;
}
.section-update-label-2 {
  color: #60bf85;
  border: 1px solid #2e3330;
}
.private-change-entry {
  position: absolute;
  right: 16px;
  font-size: 12px;
  color: #8c8c8c;
  line-height: 17px;
  cursor: pointer;
}
.private-change-entry i {
  margin-left: 4px;
}
</style>
